import { saveDialogTemplate } from '@/services/dialog';
import FlowGraph from './Graph';

export async function saveDialogGraph(dialogId,node) {
  const { graph } = FlowGraph;
  let cells = graph.toJSON().cells;
  if(node){
    cells.push(node)
  }

  let nodes = [];
  let edges = [];
  for (const cellItem of cells){
    if(cellItem.shape === 'edge'){
      edges.push(cellItem);
    }else {
      nodes.push(cellItem)
    }
  }
  //处理node
  const nodeAfterSet = [];
  for (let node of nodes){
    let obj  = {
      id : node.id.split('-')[0],
      nodeId:node.id.split('-')[0],
      size:node.size.width + '*' + node.size.height,
      modal:node.attrs.text.text,
      label:node.attrs.text.textWrap.text,
      width:node.size.width,
      height:node.size.height,
      x:node.position.x,
      y:node.position.y,
      shape:node.shape
    }
    nodeAfterSet.push(obj);
  }

  //处理edge
  const edgesAfterSet = [];
  for(let edge of edges){
    let obj = {
      id:edge.id.split('-')[0],
      source:edge.source.cell.split('-')[0],
      sourceAnchor:parseInt(edge.source.port),
      target:edge.target.cell.split('-')[0],
      targetAnchor:parseInt(edge.target.port),
      shape:edge.shape,
      annotation:edge.labels ? edge.labels[0] ? edge.labels[0] : '' : ''
    }
    edgesAfterSet.push(obj)
  }

  const res = await saveDialogTemplate({data:{nodes:nodeAfterSet,edges:edgesAfterSet},dialogId})
  console.log(res);
  if(res.code && res.code === -1){
    return false
  }else {
    return true
  }
}
